﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LGPeWJNM.DataAccessLayer
{
    public class InstanciaCsv : Instancia
    {
        public InstanciaCsv(string path)
        {
            try
            {
                using (var cnn = new System.Data.OleDb.OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"text;HDR=Yes;FMT=Delimited\";", System.IO.Path.GetDirectoryName(path))))
                using (var cmd = new System.Data.OleDb.OleDbCommand(string.Format("SELECT * FROM [{0}]", System.IO.Path.GetFileName(path)), cnn))
                {
                    using (var schemaFile = new System.IO.StreamWriter(string.Format("{0}\\schema.ini", System.IO.Path.GetDirectoryName(path)), false, System.Text.Encoding.Default))
                    {
                        schemaFile.WriteLine(string.Format("[{0}]", System.IO.Path.GetFileName(path)));
                        schemaFile.WriteLine("Format=Delimited(;)");
                    }

                    cnn.Open();
                    int i = 0;
                    var destinos = new List<LGPeWJNM.BaseClasses.Cliente>();
                    using (var r = cmd.ExecuteReader())
                        while (r.Read())
                        {
                            var cli = new LGPeWJNM.BaseClasses.Cliente()
                            {
                                Nome = (string)r[0],
                                Demanda = (int)r[1],
                                Coordenada = new BaseClasses.Point()
                                {
                                    Y = ((double)r[2]+26) * 111.096,
                                    X = ((double)r[3]+50) * 111.096
                                },
                                Id = i++
                            };
                            destinos.Add(cli);
                        }
                    this.Destinos = destinos;
                }
            }
            finally { System.IO.File.Delete(string.Format("{0}\\schema.ini", System.IO.Path.GetDirectoryName(path))); }
        }
    }
}
